package com.smart.service.impl;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import java.util.ArrayList;
import com.smart.util.StringUtil;
import com.smart.service.FileService;
import org.springframework.stereotype.Service;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;

@Service
public class FileServiceImpl implements FileService {

	@Value("${uploadPath}")
	private String fileUploadPath;
	@Value("${returnPath}")
	private String fileReturnPath;
	@Value("${deletePath}")
	private String deleteReturnPath;

	/**
	 * 上传图片
	 * @param files
	 * @return
	 **/
	@Override
	public List<String> uploadPic(MultipartFile[] files) {
		List<String> folders = upload(files);
		// 不为空就返回路径
		if (!CollectionUtils.isEmpty(folders))
			return folders;
		return null;
	}

	/**
	 * 删除图片/文件
	 * @param sourcePath
	 * @return
	 **/
	@Override
	public int removePicAndFile(String sourcePath) {
		// 删除图片
		boolean flag = new File(deleteReturnPath + sourcePath).delete();
		if (flag) {
			return 1;
		}
		return 0;
	}

	/**
	 * 上传文件
	 * @param files 文件
	 * @return
	 **/
	private List<String> upload(MultipartFile[] files) {
		List<String> stringList = new ArrayList<>();
		// 多张图片 循环存入文件夹
		for (MultipartFile file : files) {
			try {
				if (file.isEmpty()) {
					return null;
				}
				// 获取文件名
				String fileName = file.getOriginalFilename();

				// 获取文件的后缀名
				assert fileName != null;
				String suffixName = fileName.substring(fileName.lastIndexOf("."));
				File dest;
				String folder;
				// 获取当前时间戳
				String date = String.valueOf(new Date().getTime());
				// 生成8位随机数
				String random = StringUtil.getRandomString(8);
				String filename = random + date;
				fileName = filename + suffixName;
				// new文件对象
				dest = new File(fileUploadPath + "/" + fileName);
				// 拼接文件路径
				folder = fileReturnPath + fileName;
				// 检测是否存在目录
				if (!dest.getParentFile().exists()) {
					dest.getParentFile().mkdirs();
				}
				// 保存
				file.transferTo(dest);
				// 把图片路径存入list返回
				stringList.add(folder);
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
			}
		}
		return stringList;
	}

}